package com.hzjh.base.frame.activity

import android.os.Bundle
import androidx.annotation.CallSuper
import androidx.lifecycle.ViewModelProvider
import com.hzjh.base.frame.BaseViewModel
import com.hzjh.base.frame.mvvm.ViewModelFactory
import java.lang.reflect.ParameterizedType

/**
 * viewmodel 基础Activity
 */
abstract class AbsVMActivity<VM : BaseViewModel> : AbsActivity() {

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.clear()
    }

    protected lateinit var viewModel: VM

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initViewModel()
        initData()
        initView()
        initObservable()
        initLoad()
    }




    private fun initViewModel() {
        val type = javaClass.genericSuperclass
        if (type is ParameterizedType) {
            val tp = type.actualTypeArguments[1]
            val tClass = tp as? Class<VM> ?: BaseViewModel::class.java
            viewModel = ViewModelProvider(
                this.viewModelStore,
                ViewModelFactory(this)
            )[tClass] as VM
        }
    }

    /**
     * call before [initView]
     */
    abstract fun initData()

    abstract fun initView()

    abstract fun initObservable()

    @CallSuper
    open fun initLoad() {

    }


}